<template>
  <div class="tree-box">
    <!-- <el-button type="primary" @click="handleClick">提交</el-button> -->
    <a-tree
      ref="aTreeCheckAllRef"
      v-model="treeData"
      showCheckbox
      :expandOnClickNode="false"
      :defaultCheckedKeys="[5, 9]"
      @handleCheckChange="handleCheckChange"
    >
      <!-- 使用插槽增加全选反选 -->
      <template #toggleAll>
        <el-checkbox
          style="margin-left: 24px"
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
      </template>
    </a-tree>
  </div>
</template>

<script setup lang="ts">
import aTree from "@/components/aTree/index.vue";
const aTreeCheckAllRef = ref();
const checkAll = ref(false);
const isIndeterminate = ref(false);

const treeData = ref([
  {
    id: 1,
    label: "Level one 1",
    children: [
      {
        id: 4,
        label: "Level two 1-1",
        children: [
          {
            id: 9,
            label: "Level three 1-1-1",
          },
          {
            id: 10,
            label: "Level three 1-1-2",
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: "Level one 2",
    children: [
      {
        id: 5,
        label: "Level two 2-1",
      },
      {
        id: 6,
        label: "Level two 2-2",
      },
    ],
  },
  {
    id: 3,
    label: "Level one 3",
    children: [
      {
        id: 7,
        label: "Level two 3-1",
      },
      {
        id: 8,
        label: "Level two 3-2",
      },
    ],
  },
]);

// 全选反选
function handleCheckAllChange(val) {
  let handleCheck = aTreeCheckAllRef.value.treeRef;
  val
    ? handleCheck.setCheckedNodes(treeData.value)
    : handleCheck.setCheckedNodes([]);
}

// 获取选中的节点
function handleCheckChange(data, checked, indeterminate) {
  // 获取选中的数据
  let getCheckedList = aTreeCheckAllRef.value.treeRef.getCheckedNodes();
  // console.log('getCheckedList', getCheckedList)
  data.checked = checked;
  if (checked) {
    checkAllNodes();
    isIndeterminate.value = checkAll.value ? false : true;
  } else {
    checkAll.value = false;
    isIndeterminate.value = getCheckedList.length ? true : false;
  }
}

function checkAllNodes() {
  checkAll.value = treeData.value.every((node) => node.checked); // 检查所有节点是否都被选中
}

function handleClick() {
  let getCheckedList = aTreeCheckAllRef.value.treeRef.getCheckedNodes();
  console.log('getCheckedList', getCheckedList)
}
</script>

<style lang="scss" scoped>

</style>